package com.LeeCode;

import java.util.Arrays;

/**
 * 在排序数组中查找元素的第一个和最后一个位置
 */
public class Code034 {
    public static void main(String[] args) {
//        int[] nums = {5,7,7,8,8,10};
        int[] nums = {1, 1, 1, 1};
        int target = 1;
        int[] res;
        res = new Code034().searchRange1(nums, target);
        System.out.println(Arrays.toString(res));

    }

    public int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        int left = 0, right = nums.length - 1, mid;
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] == target) {
                int begin = mid, end = mid;
                while (begin >= 0 && nums[begin] == target) {
                    begin--;
                }
                while (end < nums.length && nums[end] == target) {
                    end++;
                }
                res[0] = begin + 1;
                res[1] = end - 1;
                return res;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return res;
    }

    public int[] searchRange1(int[] nums, int target) {
        int start = lowerBound(nums, target);
        if (start == nums.length || nums[start] != target) {
            return new int[]{-1, -1};
        }
        int end = lowerBound(nums, target + 1) - 1;
        return new int[]{start, end};
    }

    private int lowerBound(int[] nums, int target) {
        int left = -1, right = nums.length;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return right;
    }

}
